<template>
    <div class="my-info-container">
        <div class="user-info-container">
            <div class="info">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                    <el-form-item label="姓名" prop="realname">
                        <el-input v-model="form.realname" disabled style="width: 306px;"></el-input>
                    </el-form-item>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" disabled style="width: 306px;"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱地址" prop="ss">
                        <el-input v-model="form.email" style="width: 306px;"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="mobile">
                        <el-input v-model="form.mobile" style="width: 306px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="text" @click="dialogEditPassVisible = true">修改密码</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <div class="avatar-container">
                <el-upload
                    class="avatar-uploader"
                    action
                    :show-file-list="false"
                    :auto-upload="true"
                    :on-change="handleChange"
                    :http-request="handleOssUpload"
                    :before-upload="beforeUpload"
                >
                    <div class="avatar-box">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-if="showPlus" class="el-icon-plus avatar-uploader-icon"></i>
                        <el-progress
                            v-if="showProgress"
                            type="circle"
                            :percentage="percent"
                            class="avatar-uploader-percentage"
                        ></el-progress>
                    </div>
                </el-upload>
            </div>
        </div>
        <div class="user-info-bto">
            <el-button>取消</el-button>
            <el-button type="primary" @click="updateInfo">保存</el-button>
        </div>

        <el-dialog
            title="修改密码"
            :visible.sync="dialogEditPassVisible"
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            @close="resetEditPasswordForm"
        >
            <el-form
                :model="editPasswordForm"
                :rules="editPasswordRules"
                ref="editPasswordForm"
                labelPosition="right"
                labelWidth="100px"
                style="width: 400px"
            >
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="editPasswordForm.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="editPasswordForm.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="rePass">
                    <el-input v-model="editPasswordForm.rePass"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditPassVisible = false">取 消</el-button>
                <el-button type="primary" @click="updatePassword">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { updatedMyInfo, updateMyPassword, updateMyAvatar } from '@/api/admin/sysuser'
import { getToken } from "@/libs/auth";
import OSS from 'ali-oss'
import config from '@/config'
import { getRand } from "@/libs/utils"
export default {
    name: "my-info",
    computed: {
        ...mapGetters(['user', 'roles', 'permissions', 'access'])
    },
    mounted: function () {
        this.$nextTick(function () {
            this.form = Object.assign({}, this.user)
            this.editPasswordForm.id = this.form.id
            if (this.form.avatar) {
                this.showPlus = false
                this.showProgress = false
                this.imageUrl = this.form.avatar
            }
            //初始化Aliyun OSS
            this.client = new OSS(config.Aliyun.oss);
        })
    },
    data() {
        const validPhone = (rule, value, callback) => {
            var re = /^1[0-9]{10}$/;
            if (!re.test(value)) {
                callback(new Error('请输入正确格式的手机号'));
            } else {
                callback();
            }
        }
        const validRePassword = (rule, value, callback) => {
            if (value !== this.editPasswordForm.newPassword) {
                callback(new Error('两次输入密码不一致'));
            } else {
                callback();
            }
        }
        return {
            imageUrl: '',
            showPlus: true,
            showProgress: false,
            client: null,
            percent: 0,
            form: {},
            rules: {
                realName: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '邮件地址不能为空', trigger: 'blur' },
                    { type: 'email', message: '邮件格式不正确', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号码' },
                    { validator: validPhone }
                ]
            },
            editPasswordRules: {
                oldPassword: [
                    { required: true, message: '请输入原密码', trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, message: '请至少输入6个字符', trigger: 'blur' },
                    { max: 32, message: '最多输入32个字符', trigger: 'blur' }
                ],
                rePass: [
                    { required: true, message: '请再次输入新密码', trigger: 'blur' },
                    { validator: validRePassword, trigger: 'blur' }
                ]
            },

            dialogEditPassVisible: false, // 修改密码Dialog
            editPasswordForm: {
                oldPassword: '',
                newPassword: '',
                rePass: ''
            }
        }
    },
    methods: {
        handleOssUpload(option) { //阿里云OSS文件上传
            let self = this
            try {
                this.client.multipartUpload(getRand(), option.file, {
                    progress: async function (p, checkpoint) {
                        self.percent = p * 100
                    },
                    meta: { year: 2017, people: 'test' },
                    mime: 'image/jpeg'
                }).then(result => {
                    if (result.res.statusCode === 200) {
                        self.form.avatar = result.res.requestUrls[0].split('?')[0]
                        setTimeout(() => {
                            this.showProgress = false
                        }, 500)
                        setTimeout(() => {
                            this.imageUrl = URL.createObjectURL(option.file);
                        }, 600)
                        this.$notify({ title: '提示', message: `文件上传成功，请保存生效。<a href='${self.form.avatar}' target='_blank'>点击访问</a>`, type: 'success', dangerouslyUseHTMLString: true });
                    } else {
                        this.$notify({ title: '提示', message: '文件上传失败', type: 'error' });
                    }
                })
            } catch (e) {
                console.log(e);
            }
        },
        handleChange(file, fileList) { // 添加文件、上传成功和上传失败时都会被调用
            this.percent = 0
            this.showPlus = false
            this.showProgress = true
            this.imageUrl = ''
        },
        beforeUpload(file) { // 上传文件之前，若返回 false 或者返回 Promise 且被 reject，则停止上传
            console.log('上传前验证图片格式和大小');
        },
        updateInfo() {  //修改信息
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let self = this
                    console.log(this.form);
                    updatedMyInfo(this.form).then(response => {
                        if (response.data.status === 200) {
                            this.$store.dispatch('FedLogOut').then(() => {
                                this.$alert('修改成功，请重新登录', '提示', {
                                    confirmButtonText: '重新登陆',
                                    callback: () => {
                                        this.$loading({
                                            lock: true,
                                            text: '正在退出，请稍等...',
                                            background: 'rgba(0, 0, 0, 0.7)'
                                        });
                                        setTimeout(() => {
                                            window.location.reload()
                                        }, 500)

                                    }
                                })
                            })
                        } else if (response.data.status === 601) {
                            this.$notify({
                                title: '提示', message: response.data.msg,
                                type: 'warning', duration: 2000
                            })
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.msg,
                                type: 'error', duration: 2000
                            })
                        }
                    }).catch(error => { })
                }
            })
        },
        updatePassword() { //修改密码
            this.$refs['editPasswordForm'].validate((valid) => {
                if (valid) {
                    updateMyPassword(this.editPasswordForm).then(response => {
                        if (response.data.status === 200) {
                            this.dialogEditPassVisible = false
                            this.$notify({
                                title: '提示', message: '操作成功',
                                type: 'success', duration: 2000
                            })
                        } else if (response.data.status === 601) {
                            this.$notify({
                                title: '提示', message: response.data.msg,
                                type: 'warning', duration: 2000
                            })
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.msg,
                                type: 'error', duration: 2000
                            })
                        }
                    }).catch(error => { })
                }
            })
        },

        resetEditPasswordForm() {
            this.$refs['editPasswordForm'].resetFields()
            this.editPasswordForm = {
                id: this.user.id,
                oldPassword: '',
                newPassword: '',
                rePass: ''
            }
        },

    }
}
</script>
<style>
</style>
<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
.my-info-container {
    padding: 20px;
    .user-info-container {
        display: flex;
        flex-direction: row;
        .info {
            margin-right: 100px;
        }
    }
    .user-info-bto {
        margin-left: 35px;
    }
}

.avatar-container {
    display: flex;
    justify-content: center;
}
.avatar-uploader {
    .el-upload {
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
